from typing import Counter
from django.core import exceptions
from django.db.models.expressions import Value
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from random import randint
import json
from myapp import models
from django.core import serializers
from media import *
# from myapp.facenet import facenet
# import tensorflow as tf
import os
import re
import base64
from myapp.models import Attendentce, Worker#, file_delete
from myweb.settings import MEDIA_ROOT
from myweb.settings import WEB_HOST_MEDIA_URL
from datetime import date, datetime
from hashlib import sha1

# from myapp.facenet import FaceNet
# import tensorflow as tf
# tf.keras.backend.clear_session()


# Create your views here.

# 模型
# print('初始化')
# model = FaceNet(
#     worker_id_dir='D:/WeChat/download/WeChat Files/wxid_hyxc5wzmnklm12/FileStorage/File/2022-01/test',
#     embeddings_txt_dir='D:/WeChat/download/WeChat Files/wxid_hyxc5wzmnklm12/FileStorage/File/2022-01/test',
#     models_base_path='D:\\Code\\Python_code\\test\\myweb\\myapp\\models')
# print("初始化成功")
# 上传图片方法 name是数据库字段， dir_name是保存的文件名


def images(request, name, dir_name):
    urls = ''
    dirs = os.path.join(MEDIA_ROOT, dir_name)
    data = json.loads(request.body)
    if not os.path.isdir(dirs):
        os.makedirs(dirs)  # 判断目录是否存在，不存在则创建
    for img in data[name]:
        strs = img.split(',')
        suffix = re.findall(r'/(\w+?);', strs[0])[0]  # 取得文件后缀
        # 拼接服务器上的文件名
        img_name = sha1(img.encode()).hexdigest()[:10] + str(randint(10000,99999)) + "." + suffix
        img_path = os.path.join(dirs, img_name)
        with open(img_path, 'wb') as out:
            out.write(base64.b64decode(strs[1]))  # base64解码，再写入文件
            out.flush()
            # 拼接URL，URL与URL之间用[/--sp--/]隔开
            urls += os.path.join(WEB_HOST_MEDIA_URL,
                                 dir_name, img_name) + '[/--sp--/]'
        # result = {}
        # result['status'] = status.HTTP_200_OK
        # result['message'] = '图片上传成功'
        # result['urls'] = urls[:len(urls) - len('[/--sp--/]')]

        # 去掉末尾的[/--sp--/]
    # return JsonResponse({"status": "HTTP_200_OK", "msg": "图片上传成功"})
    return urls

# 上班拍照


def satt(request):
    req = json.loads(request.body)
    update_id = req['workerId']
    try:
        update_obj = models.Worker.objects.get(workerid=update_id)
        perimage_url = images(request, 'perimage', 'perimage')
        new_satt = models.Attendentce(
            workerid=update_obj, perimage=perimage_url, Sattdate=req['sattDate'])

        new_satt.save()
        return JsonResponse({"status": "BS.200", "msg": "satt success"})
    except:
        return JsonResponse({"status": "BS.300", "msg": "satt faild"})

# 下班拍照


def eatt(request):
    req = json.loads(request.body)
    update_id = req['workerId']
    try:
        update_obj = models.Worker.objects.get(workerid=update_id)
        update_eatt = models.Attendentce.objects.get(
            workerid=update_obj, SattData=req['sattDate'])
        update_eatt.Eattdate = req['eattDate']
        update_eatt.attdata = req['attData']
        update_eatt.save()
        return JsonResponse({"status": "BS.200", "msg": "eatt success"})
    except:
        return JsonResponse({"status": "BS.2300", "msg": "eatt faild"})

# 新增员工


def add_worker(request):
    if request.method == "POST":
        req = json.loads(request.body)
        key_flag = req.get("workerId") # and req.get("workerName") and req.get(
        #     "type") and req.get("idImageBack") and req.get("idImageFront") and req.get("icon")
        # 判断是否存在工号重复
        if key_flag:# not models.Worker.objects.get(workerid=key_flag):
            workerId = req["workerId"]
            # print('id:', workerId)
            workerName = req["workerName"]
            type = req["type"]
            # 获得头像存到本地并且保存到数据库
            icon_url = images(request, 'icon', 'icon')
            # 模型注册
            icons_url = str(icon_url).replace('http://127.0.0.1:8000', '.')
            icons_url = str(icons_url).replace('\\', '/')
            icons_url = list(str(icons_url).split('[/--sp--/]')[:-1])
            print('url:', icons_url)
            model.register(worker_id=1, image_paths=['media\icon\8014f4bb0d93931.png'])
            # 获得身份证照片
            idb_url = images(request, 'idimageback', 'idimageback')
            idf_url = images(request, 'idimagefront', 'idimagefront')
            '''插入数据'''
            add_wrk = Worker(workerid=workerId, workername=workerName, type=type, icon=icon_url, idimageback=idb_url, idimagefront=idf_url
                             )
            add_wrk.save()
            # 插入考勤数据库
            # satt = models.Worker.objects.get(workerid=workerId)
            # new_satt = models.Attendentce(
            # workerid=satt, Sattdate=req['sattDate'])
            # new_satt.save()

            return JsonResponse({"status": "BS.200", "msg": "publish worker success"})
        else:
            return JsonResponse({"status": "BS.400", "message": "error"})


# 修改员工
def update_worker(request):
    req = json.loads(request.body, strict=False)
    # 找到匹配的id
    update_id = req['workerId']
    try:
        update_obj = models.Worker.objects.get(workerid=update_id)

        new_workerName = req['workerName']
        new_type = req['type']
        print(update_obj.idimagefront)
    # 更新
    # file_delete(instance=update_obj)
    # if os.path.isfile(update_obj.idimagefront):
    #     os.remove(update_obj.idimagefront)
        update_obj.workername = new_workerName
        update_obj.icon = images(request, 'icon', 'icon')
        update_obj.type = new_type
        update_obj.idimageback = images(request, 'idimageback', 'idimageback')
        update_obj.idimagefront = images(request, 'idimagefront', 'idimagefront')
        # 保存数据库
        update_obj.save()
        return JsonResponse({"status": "BS.200", "msg": "update worker success"})
    except:
        return JsonResponse({"status": "BS.300", "msg": "update worker faild"})


# 查询所有员工
def query_worker(request):
    if request.method == "GET":
        # query_worker=Worker.objects.all()
        # workers = serializers.serialize("json", query_worker)
        query_worker = list(Worker.objects.all().values())
        print(str(Worker.objects.values("icon")).split('[/--sp--/]'))
        return JsonResponse({"status": "BS.200", "all_workers": query_worker, "msg": "query workers success."})
    else:
        return JsonResponse({"status": "BS.300", "msg": "query fail"})


# 删除工人
def delete_worker(request):
    # 从前端获得被删除工人的id
    req = json.loads(request.body)
    # for id in req["ids"]:
    # print(req["ids"])
    # 找到就删除

    test = Worker.objects.filter(pk__in=req['ids'])
    # file_delete(instance=test)
    for i in test:
        for filename in i.icon.split('[/--sp--/]')[:-1]:
            (_, tempfilename) = os.path.split(filename)
            imgFile = os.path.join(MEDIA_ROOT, 'icon', tempfilename)
            print("删除:", imgFile)
            os.remove(imgFile)

    test.delete()
    return JsonResponse({"status": "BS.200", "msg": f"delete {test.count()} worker"})

# 日考勤统计


def att(request):
    req = json.loads(request.body, strict=False)
    if request.method == "POST":
        workers = {}
        all_workers = Worker.objects.all()
        query_atts = Attendentce.objects.filter(attData=req['attData'])
        # 初始值
        total = 0
        for worker in all_workers:
            total += 1
            workers[worker.workername] = False
        # 计算应到人数
        count = 0
        for att in query_atts:
            count += 1
            workers[att.workerid.workername] = True
            # if (i.workerId.SattData&&i.workersId.EattData):
            #     flag = 1

        print(workers)
        return JsonResponse({"status": "BS.200", "message": workers, "total":total, "count":count})




# 返回图片链接

def img_url(request):
    if request.method == "POST":
        req = json.loads(request.body)
        # query_worker=Worker.objects.all()
        # workers = serializers.serialize("json", query_worker)
        # query_worker = list(Worker.objects.values("icon"))
        update_obj = models.Worker.objects.get(workerid=req['workerId'])
        img_url = str(update_obj.icon).split('[/--sp--/]')
        idimageback_url = str(update_obj.idimageback).split('[/--sp--/]')
        idimagefront_url = str(update_obj.idimagefront).split('[/--sp--/]')
        print(img_url)
        return JsonResponse({"status": "BS.200", "icon": img_url,
        "idimageback":idimageback_url,"idimagefront":idimagefront_url})
